package service4admin

import (
	"Gin-Gorm-boke/boke_admin/models4admin"
	"Gin-Gorm-boke/boke_common/helper"
	"Gin-Gorm-boke/boke_common/models"
	"Gin-Gorm-boke/boke_common/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/jinzhu/copier"
	"strconv"
)

type UserInfoDto struct {
	Id          null.Int   `gorm:"column:id;" json:"id"`
	UserName    string     `json:"userName"`
	Password    string     `json:"password"`
	NickName    string     `json:"nickName"`
	Email       string     `json:"email"`
	Sex         string     `json:"sex"`
	Status      string     `json:"status"`
	Phonenumber string     `json:"phonenumber"`
	RoleIds     []null.Int `json:"roleIds"`
}

func GetUserList(c *gin.Context) {
	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	userName := c.Query("userName")
	phonenumber := c.Query("phonenumber")
	status := c.Query("status")
	db := models.Db.Model(new(models.User))
	var total int64
	var userList []models.User
	if userName != "" {
		db.Where("user_name like ?", "%"+userName+"%")
	}
	if phonenumber != "" {
		db.Where("phonenumber like ?", "%"+phonenumber+"%")
	}
	if status != "" {
		db.Where("status = ?", status)
	}
	db.Count(&total)
	db.Order("id asc").Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&userList)
	response.ResponseOK(c, gin.H{
		"total": total,
		"rows":  userList,
	})
	return
}

func SaveUser(c *gin.Context) {
	var userInfo UserInfoDto
	if err := c.ShouldBindJSON(&userInfo); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	var user models.User
	copier.Copy(&user, &userInfo)
	roleIds := userInfo.RoleIds
	user.Password, _ = helper.GetBcryptPassword(user.Password)
	models.Db.Model(new(models.User)).Create(&user)
	for _, roleId := range roleIds {
		models.Db.Model(new(models4admin.UserRole)).Create(&models4admin.UserRole{
			UserId: user.Id,
			RoleId: int(roleId.Int64),
		})
	}
	response.ResponseOK(c, nil)
	return
}

func UpdateUser(c *gin.Context) {
	var userInfo UserInfoDto
	if err := c.ShouldBindJSON(&userInfo); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	var user models.User
	copier.Copy(&user, &userInfo)
	if userInfo.Password != "" {
		user.Password, _ = helper.GetBcryptPassword(userInfo.Password)
	}
	models.Db.Model(new(models.User)).Where("id=?", user.Id).Updates(&user)
	roleIds := userInfo.RoleIds
	if len(roleIds) > 0 {
		sql := "delete from sys_user_role where user_id=?"
		models.Db.Exec(sql, user.Id)
	}
	for _, roleId := range roleIds {
		models.Db.Model(new(models4admin.UserRole)).Create(&models4admin.UserRole{
			UserId: user.Id,
			RoleId: int(roleId.Int64),
		})
	}

}

func DelUser(c *gin.Context) {
	userId, exists := c.Get("userId")
	id, _ := strconv.Atoi(c.Param("id"))
	if !exists {
		fmt.Println("userId不存在")
		response.RespnseLoginError(c)
		return
	}
	if id == userId.(int) {
		response.ResponseBadRequest(c)
		return
	}
	models.Db.Model(new(models.User)).Where("id=?", id).Update("del_flag", "1")
	models.Db.Model(new(models.User)).Where("id=?", id).Delete(&models.User{})
	response.ResponseOK(c, nil)
	return
}

func GetUserById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	var user models.UserVo
	var roles []models4admin.RoleVo
	var roleIds []string
	models.Db.Model(new(models.UserVo)).Where("id=?", id).First(&user)
	models.Db.Model(new(models4admin.UserRole)).Select("role_id").Where("user_id=?", id).Find(&roleIds)
	models.Db.Model(new(models4admin.RoleVo)).Find(&roles)
	response.ResponseOK(c, gin.H{
		"roleIds": roleIds,
		"user":    user,
		"roles":   roles,
	})
	return
}

func ChangeStatus(c *gin.Context) {
	var user models.User
	if err := c.ShouldBindJSON(&user); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	models.Db.Model(new(models.User)).Where("id=?", user.UserId).Update("status", user.Status)
	response.ResponseOK(c, nil)
	return
}
